package hu.genius.view.adapters;

import java.util.List;

import hu.genius.R;
import hu.genius.model.entity.Product;
import hu.genius.view.utils.ViewUtils;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ProductItemAdapter extends ArrayAdapter<Product> {
	private List<Product> products;

	public ProductItemAdapter(Context context, int textViewResourceId,
			List<Product> objects) {
		super(context, textViewResourceId, objects);
		this.products = objects;
	}

	public ProductItemAdapter(Context context, int resource,
			int textViewResourceId, List<Product> objects) {
		super(context, resource, textViewResourceId, objects);
		this.products = objects;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		View v = convertView;
		if (v == null) {
			LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
					Context.LAYOUT_INFLATER_SERVICE);
			v = vi.inflate(R.layout.listview_product_item_layout, null);
		}

		Product product = products.get(position);
		if (product != null) {
			TextView productNameTextView = (TextView) v
					.findViewById(R.id.productNameTextView);
			TextView productPrice = (TextView) v
					.findViewById(R.id.productPriceTextView);

			ImageView productView = (ImageView) v.findViewById(R.id.avatar);
			if (product.getImage() != null) {
				productView.setImageBitmap(ViewUtils.downloadImage(product.getImage()));
			} else {
				productView.setImageBitmap(ViewUtils.loadImage(this.getContext(), product.getId() + "s110c" + product.getPrice() + ".00i"));
			}
			productView.setLayoutParams(new LinearLayout.LayoutParams(
					ViewUtils.getDpSize(this.getContext(), 110), ViewUtils.getDpSize(this.getContext(), 110)));
			
			if (productNameTextView != null) {
				productNameTextView.setText(product.getName());
			}

			if (productPrice != null) {
				productPrice.setText("Price: " + product.getPrice());
			}
		}
		return v;
	}

}
